package com.ibeeking.found.cop.b.rest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ibeeking.found.cop.b.rest.service.IMsgMessageTaskFriendsService;
import com.ibeeking.found.cop.b.rest.service.IWxOpenService;
import com.ibeeking.found.cop.service.common.dos.CopEmployeeDO;
import com.ibeeking.found.cop.service.common.dos.MsgMessageTaskFriendsDO;
import com.ibeeking.found.cop.service.common.query.MsgMessageTaskFriendsQuery;
import com.ibeeking.found.cop.service.common.vo.MsgMessageTaskFriendsVO;
import com.ibeeking.found.cop.service.mapper.CopEmployeeMapper;
import com.ibeeking.found.cop.service.mapper.MsgMessageTaskFriendsMapper;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.date.DateUtil;
import com.ibeeking.nematos.utils.json.JsonUtils;
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.external.contact.WxCpGroupMsgSendResult;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName MsgMessageTaskFriendsServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-01-27 18:50
 **/
@Service
public class MsgMessageTaskFriendsServiceImpl extends ServiceImpl<MsgMessageTaskFriendsMapper, MsgMessageTaskFriendsDO> implements IMsgMessageTaskFriendsService {

    @Resource
    private MsgMessageTaskFriendsMapper msgMessageTaskFriendsMapper;

    @Resource
    private CopEmployeeMapper copEmployeeMapper;

    @Resource
    private IWxOpenService wxOpenServiceImpl;

    @Override
    public List<MsgMessageTaskFriendsVO> list(MsgMessageTaskFriendsQuery query) {
        List<MsgMessageTaskFriendsDO> entityDOS = msgMessageTaskFriendsMapper.selectList(new LambdaQueryWrapper<MsgMessageTaskFriendsDO>()
                .eq(query.getId() != null, MsgMessageTaskFriendsDO::getId, query.getId())
                .eq(StringUtils.isNotBlank(query.getMessageCode()), MsgMessageTaskFriendsDO::getMessageCode, query.getMessageCode())
                .eq(query.getMessageId() != null, MsgMessageTaskFriendsDO::getMessageId, query.getMessageId())
        );
        List<MsgMessageTaskFriendsVO> entityVOS =JsonUtils.jsonToList(entityDOS, MsgMessageTaskFriendsVO.class);
        return entityVOS;
    }

    @Override
    public MsgMessageTaskFriendsVO queryById(Long id) {
        MsgMessageTaskFriendsDO entityDO = msgMessageTaskFriendsMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");
        MsgMessageTaskFriendsVO entityVO = BeanUtil.convertBean(entityDO, MsgMessageTaskFriendsVO.class);
        return entityVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean syncMessageTaskFriendsListFromWxCp(Integer tenantId, String chatType, List<String> messageCodeList, Map<String, List<String>> senderCodeMap){
        if(Collections3.isNotEmpty(messageCodeList)) {
             WxCpService wxCpService = wxOpenServiceImpl.getWxCpService(tenantId.longValue());
            WxCpConfigStorage wxCpConfigStorage = wxCpService.getWxCpConfigStorage();
            if (wxCpConfigStorage == null) {
                throw new BusinessException("获取企微服务失败!");
            }

            WxCpExternalContactService wxCpExternalContactService = wxCpService.getExternalContactService();
            if (wxCpExternalContactService == null) throw new BusinessException("获取企微服务外部联系人服务!");
            List<CopEmployeeDO> copEmployeeDOS = copEmployeeMapper.selectList(new LambdaQueryWrapper<>());
            Map<String, Long> copEmployeeNameMaps = Collections3.isNotEmpty(copEmployeeDOS)?copEmployeeDOS.stream().collect(Collectors.toMap(CopEmployeeDO::getEmployeeCode, CopEmployeeDO::getId, (o, n) -> n)):null;
            List<MsgMessageTaskFriendsDO> allMsgMessageTaskFriendsDOS = new ArrayList<>();
            for (String messageCode : messageCodeList) {
                List<MsgMessageTaskFriendsDO> messageTaskFriendsDOS = msgMessageTaskFriendsMapper.selectList(new LambdaQueryWrapper<MsgMessageTaskFriendsDO>().eq(MsgMessageTaskFriendsDO::getMessageCode, messageCode));
                Map<String, MsgMessageTaskFriendsDO> messageTaskFriendsMap = Collections3.isNotEmpty(messageTaskFriendsDOS)?messageTaskFriendsDOS.stream().collect(Collectors.toMap(MsgMessageTaskFriendsDO::getFriendsCode, x->x, (o, n) -> n)):null;

                List<String> senderList = senderCodeMap!=null?senderCodeMap.get(messageCode):null;
                if(Collections3.isNotEmpty(senderList)) {
                    for(String senderCode:senderList) {
                        try {
                            String nextCursor = null;
                            do {
                                WxCpGroupMsgSendResult wxCpGroupMsgSendResult  = wxCpExternalContactService.getGroupMsgSendResult(messageCode, senderCode,800, nextCursor);
                                if(wxCpGroupMsgSendResult!=null){
                                    nextCursor = wxCpGroupMsgSendResult.getNextCursor();
                                    List<WxCpGroupMsgSendResult.ExternalContactGroupMsgSendInfo> customerItemList = wxCpGroupMsgSendResult.getSendList();
                                    if(Collections3.isNotEmpty(customerItemList)){
                                        for(WxCpGroupMsgSendResult.ExternalContactGroupMsgSendInfo customerItem: customerItemList){
                                            String friendsCode = customerItem.getExternalUserId();
                                            String rtnSenderCode = customerItem.getUserId();
                                            String rtnChatId = customerItem.getChatId();
                                            Integer sendStatus = customerItem.getStatus();
                                            Long sendTime = customerItem.getSendTime();
                                            if(StringUtils.isNotEmpty(friendsCode)){
                                                if(messageTaskFriendsMap!=null && messageTaskFriendsMap.containsKey(friendsCode)) {
                                                    MsgMessageTaskFriendsDO MsgMessageTaskFriendsDO = messageTaskFriendsMap.get(friendsCode);
                                                    MsgMessageTaskFriendsDO.setChatId(rtnChatId);
                                                    MsgMessageTaskFriendsDO.setSendStatus(sendStatus);
                                                    MsgMessageTaskFriendsDO.setSenderCode(senderCode);
                                                    if(copEmployeeNameMaps!=null && copEmployeeNameMaps.containsKey(senderCode)) {
                                                        MsgMessageTaskFriendsDO.setSenderId(copEmployeeNameMaps.get(senderCode));
                                                    }
                                                    if(sendTime!=null){
                                                        MsgMessageTaskFriendsDO.setSendTime(DateUtil.longToLocalDateTime(sendTime));
                                                    }

                                                    allMsgMessageTaskFriendsDOS.add(MsgMessageTaskFriendsDO);
                                                }
                                            }
                                        }
                                    }
                                }else{
                                    nextCursor = null;
                                }
                            } while (nextCursor == null);
                        } catch (Exception e) {
                            LogUtils.error("获取客户朋友圈发表后的可见客户列表异常，原因：{}",e);
                            return false;
                        }
                    }
                }
            }
            if(Collections3.isNotEmpty(allMsgMessageTaskFriendsDOS)){
                super.updateBatchById(allMsgMessageTaskFriendsDOS);
            }
        }
        return true;
    }
}
